package com.entrogy.timing;

import com.entrogy.bean.*;
import com.entrogy.dao.*;
import com.entrogy.utils.DateUtils;
import com.entrogy.utils.SendUtils;
import com.entrogy.utils.StrUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 *
 * Description: 与StuRecordServlet对应的service 功能： 1.新增对流水记录的操作：handleRecord(int
 * id, String personName, String machineName, double time)
 * 2.新增插入流水到当天的数据库：insertIntoDataBase(int id, String personName, String
 * machineName, double time)
 *
 */
@Component
public class StuRecordService {

	private static final Logger logger = LoggerFactory.getLogger(StuRecordService.class);

	private static StuRecordService stuRecordService;

	@Autowired
	private  PassRecordMapper passRecordMapper;

	@Autowired
	private MessageMapper messageMapper;

	@Autowired
	private  AttendanceMapper attendanceMapper;

	@Autowired
	private TimingTaskService ttSer;

	@Autowired
	private SchoolMapper schoolMapper;

	@Autowired
	private StudentMapper studentMapper;

	@PostConstruct
	public void init(){
		stuRecordService = this;
		stuRecordService.attendanceMapper = this.attendanceMapper;
		stuRecordService.messageMapper = this.messageMapper;
		stuRecordService.passRecordMapper = this.passRecordMapper;
		stuRecordService.ttSer = this.ttSer;
		stuRecordService.schoolMapper = this.schoolMapper;
		stuRecordService.studentMapper = this.studentMapper;
	}

	public static Date date1; // 早上大门迟到时间
	public static Date date2; // 中午大门迟到时间
	public static Date date3; // 傍晚大门迟到时间
	public static Date date4; // 早上寝室出门迟到时间
	public static Date date5; // 中午寝室归寝迟到时间
	public static Date date6; // 中午寝室出门迟到时间
	public static Date date7; // 晚上寝室归正常考勤开始时间
	public static Date date8 = new Date(); // 晚上寝室归正常考勤结束时间也是寝室晚上入门迟到时间1
	public static Date date9 = DateUtils.getT(23, 59, 59); // 寝室晚上入门迟到结束时间

	// 更新时间点
	public void updateTime() {
		TimeEntity timeBean = stuRecordService.passRecordMapper.updateTime();
		String[] datestr = timeBean.getDate1().split(",");
		logger.info("设置考勤时间");
		date1 = DateUtils.getT(Integer.parseInt(datestr[0]), Integer.parseInt(datestr[1]),
				Integer.parseInt(datestr[2]));
		datestr = timeBean.getDate2().split(",");
		date2 = DateUtils.getT(Integer.parseInt(datestr[0]), Integer.parseInt(datestr[1]),
				Integer.parseInt(datestr[2]));
		datestr = timeBean.getDate3().split(",");
		date3 = DateUtils.getT(Integer.parseInt(datestr[0]), Integer.parseInt(datestr[1]),
				Integer.parseInt(datestr[2]));
		datestr = timeBean.getDate4().split(",");
		date4 = DateUtils.getT(Integer.parseInt(datestr[0]), Integer.parseInt(datestr[1]),
				Integer.parseInt(datestr[2]));
		datestr = timeBean.getDate5().split(",");
		date5 = DateUtils.getT(Integer.parseInt(datestr[0]), Integer.parseInt(datestr[1]),
				Integer.parseInt(datestr[2]));
		datestr = timeBean.getDate6().split(",");
		date6 = DateUtils.getT(Integer.parseInt(datestr[0]), Integer.parseInt(datestr[1]),
				Integer.parseInt(datestr[2]));
		datestr = timeBean.getDate7().split(",");
		date7 = DateUtils.getT(Integer.parseInt(datestr[0]), Integer.parseInt(datestr[1]),
				Integer.parseInt(datestr[2]));
		datestr = timeBean.getDate8().split(",");
		date8 = DateUtils.getT(Integer.parseInt(datestr[0]), Integer.parseInt(datestr[1]),
				Integer.parseInt(datestr[2]));
		logger.info("设置考勤时间结束");
	}

	/**
	 * 插入流水记录到当天的数据库 先根据machineName判断设备，然后决定是否插入和发送微信推送 ZDM和YDM随时记录，收到就推送
	 * ss1_、ss2_、ss3_和ss4_在晚上规定时间记录和推送（暂定22：00-22：30）
	 * ss1在中午和晚上规定时间记录(暂定13：00-14：30和22：30-23：59)
	 * ss2在早上和中午规定时间记录(暂定7：40-9：00和14：00-15：00)
	 * DT在离校日规定时间记录和推送(有来自这个设备的记录则说明是离校日，即来自该设备的消息随时记录)
	 **/
	public synchronized void handleRecord(int id, String personName, String machineName, Date passTime, String deviceId, String identityID, int schoolCode) {
		Date recordTime = new Date();//当前时间   --- 通知时间
		// 当前时间已经大于通行时间一天的话，该条消息不进行发送
		long currentTimeMillisecond = recordTime.getTime();
		long passTimeMillisecond = passTime.getTime();
		if (Double.valueOf(currentTimeMillisecond - passTimeMillisecond) / 86400000 <= 1){
			SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String schoolName = stuRecordService.schoolMapper.getSchoolName(schoolCode);
			String[] paramsWeiXin = {"", schoolName, "“熵熵”脸卡通", format1.format(recordTime), "", ""};
			// 处理来自大门的设备上传的流水
			if (machineName.endsWith("dm1") || machineName.endsWith("dm2")) {
				try {
					Integer openStatus = stuRecordService.schoolMapper.getSchoolOpenStatus(schoolCode);
					List<String> parentPhoneDB = stuRecordService.passRecordMapper.getParentPhone(String.valueOf(id), schoolCode);//根据学生THDID查询出其所有的家长电话号码
					if (openStatus == 1){
						sendPassRecordToParent(parentPhoneDB, paramsWeiXin, machineName, personName, format1, passTime,id);
					}else if(openStatus == 0){
						StudentBasicInfoEntity student = stuRecordService.studentMapper.getStudentByThdid(String.valueOf(id), schoolCode);
						if(stuRecordService.studentMapper.getStudentPayStatus(student.getId()) != null){
							sendPassRecordToParent(parentPhoneDB, paramsWeiXin, machineName, personName, format1, passTime,id);
						}else {
							logger.info("学生=>" + student.getStudentName() + "家长未付费，此条流水不会推送家长！");
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
					logger.error("发送进校门微信推送失败"+e.toString());
				}
				stuCancelLeaveAndSetTime(id, recordTime, schoolCode);//销假
			}

			// 处理来自宿舍的流水
			if (machineName.endsWith("ss")){
				Integer openStatus = stuRecordService.schoolMapper.getSchoolOpenStatus(schoolCode);
				List<String> parentPhoneDB = stuRecordService.passRecordMapper.getParentPhone(String.valueOf(id), schoolCode);//根据学生THDID查询出其所有的家长电话号码
				if (openStatus == 1){
					sendBackDormToParent(parentPhoneDB, paramsWeiXin, machineName, personName, format1, recordTime);
				}else if(openStatus == 0){
					StudentBasicInfoEntity student = stuRecordService.studentMapper.getStudentByThdid(String.valueOf(id), schoolCode);
					if(stuRecordService.studentMapper.getStudentPayStatus(student.getId()) != null){
						sendBackDormToParent(parentPhoneDB, paramsWeiXin, machineName, personName, format1, recordTime);
					}else {
						logger.info("学生=>" + student.getStudentName() + "家长未付费，此条流水不会推送家长！");
					}
				}
			}
		}else {
			logger.warn("学生=>{}，的流水已过期，此条流水不会推送家长！", personName);
		}
		// 通行流水入库
		insertIntoDataBase(id, personName, machineName, passTime, 1, deviceId,identityID,schoolCode);
	}

	private void sendPassRecordToParent(List<String> parentPhoneDB, String[] paramsWeiXin, String machineName, String personName, SimpleDateFormat format1, Date passTime,int id){
		if(parentPhoneDB.size() != 0){
			PubCountEntity parent1Openid;
			PubCountEntity parent2Openid = null;
			if(parentPhoneDB.size() == 1 ){// 有一个家长
				parent1Openid = stuRecordService.messageMapper.getPubCountOpenidByPhone(parentPhoneDB.get(0));
			}else{// 有两个家长
				parent1Openid = stuRecordService.messageMapper.getPubCountOpenidByPhone(parentPhoneDB.get(0));
				parent2Openid = stuRecordService.messageMapper.getPubCountOpenidByPhone(parentPhoneDB.get(1));
			}
			if (machineName.endsWith("1"))
				paramsWeiXin[4] = "家长您好!您的孩子" + personName + "已于" + format1.format(passTime) + "到达学校";
			else
				paramsWeiXin[4] = "家长您好!您的孩子" + personName + "已于" + format1.format(passTime) + "离开学校";
			// 判断是否是3分钟内的重复通行记录
			boolean isMultiplePassRecord = isMultiplePassRecord(id, passTime);
			if (null != parent1Openid && !StrUtils.isNullOrEmpty(parent1Openid.getOpenid()) && !isMultiplePassRecord) {
				SendUtils.sendByWeixin(parent1Openid, paramsWeiXin,parent1Openid.getTemplateId());
			}
			if (null != parent2Openid && !StrUtils.isNullOrEmpty(parent2Openid.getOpenid()) && !isMultiplePassRecord) {
				SendUtils.sendByWeixin(parent2Openid, paramsWeiXin, parent2Openid.getTemplateId());
			}
		}
	}

	private boolean isMultiplePassRecord(int studentThdidId, Date passTime){
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
		Date date = new Date();
		String tableName = "pass_record" + dateFormat.format(date);
        // 获取三分钟内的重复数据
        int multiplePassRecordCount = stuRecordService.passRecordMapper.countMultiplePassRecord(studentThdidId, passTime, tableName);
		return multiplePassRecordCount > 0;
	}

	private void sendBackDormToParent(List<String> parentPhoneDB, String[] paramsWeiXin, String machineName, String personName, SimpleDateFormat format1, Date record_time){
		if(parentPhoneDB.size() != 0){
			PubCountEntity parent1Openid;
			PubCountEntity parent2Openid = null;
			if(parentPhoneDB.size() == 1 ){	// 有一个家长
				parent1Openid = stuRecordService.messageMapper.getPubCountOpenidByPhone(parentPhoneDB.get(0));
			}else{	// 有两个家长
				parent1Openid = stuRecordService.messageMapper.getPubCountOpenidByPhone(parentPhoneDB.get(0));
				parent2Openid = stuRecordService.messageMapper.getPubCountOpenidByPhone(parentPhoneDB.get(1));
			}
			paramsWeiXin[4] = "家长您好!您的孩子" + personName + "已于" + format1.format(record_time) + "到达寝室";
			if (null != parent1Openid && !StrUtils.isNullOrEmpty(parent1Openid.getOpenid())) {
				SendUtils.sendByWeixin(parent1Openid, paramsWeiXin, parent1Openid.getTemplateId());
			}
			if (null != parent2Openid && !StrUtils.isNullOrEmpty(parent2Openid.getOpenid())) {
				SendUtils.sendByWeixin(parent2Openid, paramsWeiXin, parent2Openid.getTemplateId());
			}
		}
	}


	// 插入流水记录
	public synchronized void insertIntoDataBase(int id, String personName, String machineName, Date time, int flag, String deviceId,String identityID,int schoolCode) {
		// 获取当天的记录表表名，格式为pass_record20181026
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
		Date date = new Date();
		String tableName = "pass_record" + dateFormat.format(date);
		try {
			stuRecordService.passRecordMapper.insertIntoDataBase(tableName, id, personName, machineName,time, flag, deviceId,identityID,schoolCode);
		} catch (Exception e) {
			logger.error("插入流水记录失败"+e.toString());
		}
	}

	// 流水是学生的话要给请假的销假，并且恢复正常时间
	private void stuCancelLeaveAndSetTime(int stuId, Date passDate,int schoolCode) {
		StudentEntity stuBean = stuRecordService.passRecordMapper.getStudentBeanByThdid(stuId,schoolCode);
		if (stuBean != null) {
			// 是学生
			List<LeaveRecordEntity> leaveBeanList = stuRecordService.attendanceMapper.getLeaveBeanListById(stuBean.getId());
			// 一般就一个
			for (LeaveRecordEntity leaveBean : leaveBeanList) {
				if (leaveBean.getStartTime().before(passDate) && passDate.before(leaveBean.getEndTime())) {
					// 在请假时段内出校门的，要销假
					if ((stuRecordService.attendanceMapper.cancelLeaveRecordByLeaveId(leaveBean.getLeaveId()))>0) {
						// 如果销假了的，需要立马推送正常时间
						try {
							ttSer.pushTime(stuBean);
						} catch (SecurityException e) {
							e.printStackTrace();
						} catch (IllegalArgumentException e) {
							e.printStackTrace();
						}
					} else {
						logger.info(stuBean.getId() + stuBean.getStudentName() + " 销假失败");
					}
				} else {
					// 在正常时间出门的，不在请假时间段内出门的不算销假
				}
			}
		}
	}




}

